package com.hjy.exception;//package org.example.exception;

import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.hjy.common.ApiResponse;
import com.hjy.common.IgnoreMethodReturn;
import com.hjy.until.JsonUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class GlobalExceptionHandler  implements ResponseBodyAdvice {
    @ExceptionHandler(CfmsException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ApiResponse handleApiException(CfmsException ex) {
        ex.printStackTrace();
        return ApiResponse.error( ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ApiResponse handleException(Exception ex) {
        ex.printStackTrace();
        return ApiResponse.error("Internal Server Error: " + ex.getMessage());
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        if ("uiConfiguration".equals(methodParameter.getMethod().getName())||"swaggerResources".equals(methodParameter.getMethod().getName()) || "getDocumentation".equals(methodParameter.getMethod().getName())) {
            return false;
        }
        return !methodParameter.hasMethodAnnotation(IgnoreMethodReturn.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String clazz = methodParameter.getParameterType().getName();
        if (clazz.contains("ApiResponse")) {
            return body;
        } else {
            ApiResponse webAccessResult;
            if (clazz.contains("String")) {
                webAccessResult = ApiResponse.success(body);
                return JsonUtils.toJson(webAccessResult);
            } else {
                return  ApiResponse.success(body);
            }
        }
    }

}
